<template>
  <div class="attr-list">
    <el-button
      icon="el-icon-plus"
      size="small"
      type="primary"
      @click="addAttrBtn"
      :disabled="!category.category3Id"
    >
      添加属性
    </el-button>
    <br />
    <br />
    <el-table :data="tableData" border v-loading="isLoading">
      <el-table-column
        type="index"
        label="序号"
        width="100px"
        align="center"
      ></el-table-column>
      <el-table-column
        label="属性名称"
        width="200"
        prop="attrName"
      ></el-table-column>
      <el-table-column label="属性值列表">
        <template #default="{ row }">
          <el-tag
            size="mini"
            v-for="attrValue in row.attrValueList"
            :key="attrValue.id"
            class="attr-tag"
          >
            {{ attrValue.valueName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="$emit('setToAddAttrData', row)"
          ></el-button>
          <el-button
            icon="el-icon-delete"
            size="mini"
            type="danger"
            @click="delAttr(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getAttrInfoListApi, deleteAttrApi } from '@/api/product/attrApi'
export default {
  name: 'AttrList',
  data() {
    return {
      tableData: [],
      isLoading: false
    }
  },
  computed: {
    ...mapState('category', ['category'])
  },
  watch: {
    'category.category3Id': {
      handler() {
        this.getAttrList()
      },
      immediate: true
    }
  },
  methods: {
    // 封装请求数据的方法
    async getAttrList() {
      if (!this.category.category3Id) {
        this.tableData = []
        return
      }
      this.isLoading = true
      const res = await getAttrInfoListApi(
        this.category.category1Id,
        this.category.category2Id,
        this.category.category3Id
      )
      this.tableData = res.data
      this.isLoading = false
    },
    addAttrBtn() {
      this.$emit('changeShowNum', 1)
      this.$emit('setToAddAttrData', {
        attrName: '',
        attrValueList: [],
        id: undefined
      })
    },
    async delAttr(id) {
      if (!confirm('确定删除？')) return
      await deleteAttrApi(id)
      this.$message.success('删除成功')
      this.getAttrList()
    }
  }
}
</script>

<style scoped>
.attr-tag {
  margin: 0 5px;
}
</style>
